package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private RabbitService rabbitService;

    @Override
    public void updatePaymentStatus(Transaction transaction) {
        //  更新交易状态payment_info与订单order_info或充值recharge_info状态
        PaymentInfo paymentInfo = this.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, transaction.getOutTradeNo()));
        //  判断
        if (null != paymentInfo && paymentInfo.getPaymentStatus().equals(SystemConstant.PAYMENT_STATUS_UNPAID)) {
            //  修改交易状态
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
            //  设置交易号
            paymentInfo.setOutTradeNo(transaction.getTransactionId());
            this.updateById(paymentInfo);
        }
        //  订单order_info或充值recharge_info状态
        //  小三元：判断到时应该给哪一个路由键！
        String routeKey = paymentInfo.getPaymentType().equals(SystemConstant.PAYMENT_TYPE_ORDER) ? MqConst.ROUTING_ORDER_PAY_SUCCESS : MqConst.ROUTING_RECHARGE_PAY_SUCCESS;
        //  发送消息：
        rabbitService.sendMessage(MqConst.EXCHANGE_ORDER, routeKey, paymentInfo.getOrderNo());
    }

    @Override
    public void savePaymentInfo(Long userId, String paymentType, String orderNo, BigDecimal payAmount) {
        //  创建paymentInfo 对象
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setAmount(payAmount);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        String content = paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER) ? "订单付款" : "充值付款";
        paymentInfo.setContent(content);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //  保存数据
        this.save(paymentInfo);
    }
}
